package com.freeman.cement.controller;

import com.freeman.cement.annotation.NeedRole;
import com.freeman.cement.entity.MyEvent;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.myenum.EventCatlog;
import com.freeman.cement.myenum.EventHandleResult;
import com.freeman.cement.service.EventHandleService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import java.lang.NumberFormatException;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;


/**
 * 用于事件处理
 * 包括接警处理、处置处理、验收等流程的操作
 */
@RestController
@RequestMapping("/eventhandle")
@CrossOrigin    //允许跨域访问
public class EventHandleController {
    @Resource
    private EventHandleService eventHandleService;

    //region 202211

    /**
     * 值班室值班人员接警处理
     * @海康报警事件id eventId
     * @值班人员id handler
     * @值班室id dutyRoomId
     * @return
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/answerEvent", method = RequestMethod.POST)
    public ResponseResult answerEvent(@RequestParam("eventId") String eventId, @RequestParam("handler") Integer handler, @RequestParam("dutyRoomId") Integer dutyRoomId) {
        return eventHandleService.answerEvent(eventId, handler, dutyRoomId);
    }

    /**
     * ！！！
     * 关于 int 和 Integer 的使用
     * 对于接口必须要用到的int类型数据，使用int
     * 对于接口非必须用到的int类型数据，使用Integer，例如update操作时，可能会修改也可能不修改的某些int类型字段，这样方便在mbatis xml问卷中使用 isNull 判断是否需要修改该字段
     */

    /**
     * 值班室人员关闭报警
     * @param eventId
     * @param handler
     * @param dutyRoomId
     * @param catlog
     * @param describe
     * @return
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/closeEvent", method = RequestMethod.POST)
    public ResponseResult closeEvent(
            @RequestParam("eventId") String eventId, 
            @RequestParam(value = "handler", required = false) Integer handler, 
            @RequestParam(value = "dutyRoomId", required = false) Integer dutyRoomId, 
            @RequestParam(value = "catlog", required = false) String catlogStr, 
            String describe) {
        
        if (StringUtils.isBlank(eventId)) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }

        // 如果前端传入了handler和dutyRoomId，就使用前端传入的值
        if (handler != null && handler > 0 && dutyRoomId != null && dutyRoomId > 0) {
            // 使用前端传入的值
        } else {
            // 尝试从请求中获取当前用户信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                if (request != null) {
                    Integer currentUserId = (Integer) request.getAttribute("userId");
                    Integer currentDutyRoomId = (Integer) request.getAttribute("deptId");
                    
                    if (currentUserId != null && currentUserId > 0 && 
                        currentDutyRoomId != null && currentDutyRoomId > 0) {
                        handler = currentUserId;
                        dutyRoomId = currentDutyRoomId;
                    }
                }
            }
        }

        // 确保handler和dutyRoomId有值
        if (handler == null || handler <= 0 || dutyRoomId == null || dutyRoomId <= 0) {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
        
        // 处理 catlog 参数 - 允许为空，使用默认值
        Integer catlog = 0;
        try {
            if (StringUtils.isNotBlank(catlogStr)) {
                catlog = Integer.parseInt(catlogStr);
            }
        } catch (NumberFormatException e) {
            // 如果转换失败，使用默认值 0
            catlog = 0;
        }
        
        // 确保 catlog 在有效范围内
        if (catlog < 0 || catlog >= EventCatlog.values().length) {
            catlog = 0;
        }
        
        // describe 允许为空，表示无特殊说明
        if (describe == null) {
            describe = "";
        }
        
        EventCatlog cat = EventCatlog.values()[catlog];
        return eventHandleService.closeEvent(eventId, handler, dutyRoomId, cat, describe);
    }

    /**
     * 记录由值班室发出的分派报警事件后续处理情况
     * @海康给出的事件id eventId
     * @值班人员id handler
     * @值班室id dutyRoomId
     * @分配处理人的id集合，以,号分隔 nextHandler
     * @警情类型 catlog
     * @警情描述 describe
     * @return
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/assignmentRecord", method = RequestMethod.POST)
    public ResponseResult assignmentRecord(@RequestParam("eventId") String eventId, @RequestParam("handler") int handler, @RequestParam("dutyRoomId") int dutyRoomId, @RequestParam("nextHandler") String nextHandler, int catlog, String describe)
    {
        EventCatlog cat = EventCatlog.values()[catlog];
        return eventHandleService.assignment(eventId, handler, dutyRoomId, nextHandler, cat, describe);
    }

    /**
     * 目前未使用 20230222
     * 由APP用户发出的将原本分配给自己处理的报警事件转推到别的处置员处理，也就是处置员可以把分配给自己处理的报警事件转推给别人
     * @海康给出的事件id eventId
     * @原处理员/App登录用户id handler
     * @转推给新的处置人员id nextHandler
     * @return
     */
    @NeedRole("管理员||值班员||处置员")
    @RequestMapping(value = "/retransmitAssignment", method = RequestMethod.POST)
    public ResponseResult retransmitAssignment(@RequestParam("eventId") String eventId, @RequestParam("handler") int handler, @RequestParam("nextHandler") int nextHandler)
    {
        return eventHandleService.retransmitAssignment(eventId, handler, nextHandler);
    }

    /**
     * 保存值班人员对报警事件的描述
     * @param eventId
     * @param catlog
     * @param describe
     * @return
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/saveEventDescribe", method = RequestMethod.POST)
    public ResponseResult saveEventDescribe(@RequestParam("eventId") String eventId, @RequestParam("catlog") int catlog, @RequestParam("describe") String describe)
    {
        return eventHandleService.saveEventDescribe(eventId, catlog, describe);
    }

    /**
     * 处置人查询与自己相关的各个状态的报警事件:eventId为空的话，根据 userId 和事件 status 查找出分派给自己的事件详情
     * 处置人查询是否有与自己相关的待处理事件:eventId为空的话，根据 userId 和事件 status 查找出分派给自己的事件详情
     * 处置人查询某一事件的报警详情:eventId不为空的话，直接根据eventId查找出事件详情
     * @param userId
     * @param eventId
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    @NeedRole("管理员||值班员||处置员")
    @RequestMapping(value = "/getAssignmentEvent", method = RequestMethod.POST)
    public ResponseResult getAssignmentEvent(Integer userId, String eventId, Integer status, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize)
    {
        return eventHandleService.getAssignmentEvent(userId, eventId, status, pageNo, pageSize);
    }

    /**
     * 处置人处理后提交待验收
     * @param eventId
     * @param userId
     * @param opinion
     * @return
     */
    @NeedRole("管理员||值班员||处置员")
    @RequestMapping(value = "/submitEventHandle", method = RequestMethod.POST)
    public ResponseResult submitEventHandle(@RequestParam("eventId") String eventId, @RequestParam("userId") int userId, String opinion)
    {
        return eventHandleService.submitEventHandle(eventId, userId, opinion);
    }

    /**
     * 值班人员进行处理验收
     * @param eventId
     * @param userId
     * @param result
     * @param conclusion
     * @return
     */
    @NeedRole("管理员||值班员")
    @RequestMapping(value = "/confirmEventHandle", method = RequestMethod.POST)
    public ResponseResult confirmEventHandle(@RequestParam("eventId") String eventId, @RequestParam("userId") int userId, @RequestParam("result") int result, String conclusion)
    {
        EventHandleResult rslt = EventHandleResult.values()[result];
        return eventHandleService.confirmEventHandle(eventId, userId, conclusion, rslt);
    }

    //endregion

    /**
     * 20230817
     * 用于测试自动转发
     * @param eventType
     * @param cameraIndexCode
     * @param eventId
     * @return
     */
    @RequestMapping(value = "/handleNewEventTest", method = RequestMethod.POST)
    public ResponseResult handleNewEvent(@RequestParam("eventType") String eventType, @RequestParam("cameraIndexCode") String cameraIndexCode, @RequestParam("eventId") String eventId){
        MyEvent event = new MyEvent();
        event.setEventType(eventType);
        event.setCameraIndexCode(cameraIndexCode);
        event.setEventId(eventId);
        eventHandleService.handleNewEvent(event, null, null, null, null);
        return ResponseResult.successMsg("test handleNewEvent");
    }

}
